#sound module
#
# interfase:
#    init() : returns an iterator; when exhausted sound will be initialized
#             to be called only once
#    play_sfx(name, volume=1.0) : volume in range [0,1] ,
#                                 name -> one in known_sfx
#    select_song(name, play_now=True) : name in known_song
#    volume_sfx : in range [0, 1] - will multiply any sfx volume
#    volume_music : in range [0, 1] , will multiply any music volume
import itertools
import os
import pyglet

import gg

if gg.sound_available and not gg.sound_disabled:
    try:
        import pyglet.media.avbin
    except:
        gg.sound_available = False
    
sfx_dir = os.path.join('data','sfx')
known_sfx = { #name: (volume , filename)
    'pick':(1.0, 'pick.wav')
    }
sfx_cache = {}
    
music_dir = os.path.join('data','music')
known_song = {
    'stitch-n-bitch':(1.0,'virt_-_stitch-n-bitch.mp3')
    }
song_cache = {}

_sfx_volume = .25
_music_volume = .250
current_song = None
_music_player = None

def init():
    init_steppers = [_init_sfx(), _init_music()]
    it = itertools.chain( *init_steppers )
    return it

def play_sfx(name, volume=1.0):
    if gg.sound_available and _sfx_volume:
        _play_sfx(name, volume*_sfx_volume)
        print 'playing sound:', name


def select_song(name, play_now=True):
    global current_song, music_player
    if name == current_song:
        return
    if name in known_song:
        if gg.sound_available and _music_volume:
            song_media , volume_factor = song_cache[name]
            volume = volume_factor * _music_volume
            song_media.volume = volume
            if play_now:
                music_player = song_media.play()
                music_player.volume = volume
                print 'playing song:',name
            current_song = name
        
def set_volume(variant, volume):
    global _music_volume, _sfx_volume
    if not gg.sound_available:
        return
    setattr(gg, variant)
    _music_volume = gg.music_volume * gg.general_volume
    _sfx_volume = gg.sfx_volume * gg.general_volume
    if (variant=='music_volume'):
        music_player.volume = _music_volume

    
# iterator style to no block screen updates 
def _init_sfx():
    if not gg.sound_available:
        raise StopIteration
    #cache sfx's
    for name in known_sfx:
        volume , filename = known_sfx[name]
        fname = os.path.join(sfx_dir,filename)
        print 'abspath:',os.path.abspath(fname)
        sfx_cache[name] = (pyglet.media.load(fname, streaming=False),
                           volume)
        yield

def _init_music():
    if not gg.sound_available:
        raise StopIteration
    #preload - 
    for name in known_song:
        volume , filename = known_song[name]
        fname = os.path.join(music_dir,filename)
        song_cache[name] = (pyglet.media.load(fname, streaming=True),
                            volume)
        yield
    

def _play_sfx(name, volume):
    media , volume_factor = sfx_cache[name]
    volume = volume * volume_factor
    media.volume = volume
    media.play().volume = volume

def test():
    import time
    global pyglet
    os.chdir('..')
    window = pyglet.window.Window()

    @window.event
    def on_draw():
        window.clear()

    @window.event
    def on_resize(width, height):
        gg.sound_available = True
        gg.sound_disabled = True
        try:
            import pyglet.media.avbin
        except:
            gg.sound_available = False
        for e in init():
            pass
        play_sfx('pick')
        select_song('stitch-n-bitch')


    pyglet.gl.glClearColor(1, 1, 1, 1)

    pyglet.app.run()

if __name__ == '__main__':
    test()

